const pool = require('../tools/getPool');
const sendResponse = require('../tools/sendResponse');

module.exports = function(req, res){

	let type 		= req.body.type;
	let medicine_id = req.body.medicine_id;
	let amout 		= req.body.amout;
	let message 	= req.body.message;
	let remarks 	= req.body.remarks;

	// TODO
	let clerk_id 	= req.session.id || 1;

	if (type == undefined || medicine_id == undefined || amout == undefined) {
		sendResponse('error','params lack', null, res);
		return;
	}

	if (!(type == 'purchase' || type == 'sale' || type == 'refund' || type == 'damage')) {
		sendResponse('error','params type error', null, res);
		return;
	}

	if (type != 'purchase') {
		amout = -amout;
	}

	pool.getConnection(function(err, connection) {
		
		if (err) { 
			sendResponse('error',err, null, res);
			return;
		}

		connection.beginTransaction(function(err) {
			if (err) { 
				sendResponse('error',err, null, res);
				return;
			}
			connection.query('SELECT amout FROM medicine WHERE id = ?', [medicine_id], function (error, rows, fields) {
				if (error) {
					connection.release();
					sendResponse('error',error, null, res);
					return;
				}

				if (rows.length != 1) {
					connection.release();
					sendResponse('error','database error 2', null, res);
					return ;
				}

				if (type != 'purchase' && -amout > rows[0].amout) {
					connection.release();
					sendResponse('error','too much', null, res);
					return ;
				} 

				connection.query('UPDATE medicine SET amout = amout + ? WHERE id = ?', [amout, medicine_id], function (error, rows, fields) {
					if (error) {
						connection.rollback();
						sendResponse('error',error, null, res);
						return ;
					}
					connection.query('INSERT INTO bill(type, medicine_id, clerk_id, amout, message, remarks) VALUES(?,?,?,?,?,?)', [type, medicine_id, clerk_id, amout, message, remarks], function (error, rows, fields) {
						if (error) {
							connection.rollback();
							sendResponse('error',error, null, res);
							return ;
						}
						connection.commit(function(err) {
							if (err) {
								connection.rollback();
								sendResponse('error',err, null, res);
								return ;
							}
							sendResponse('ok','success', null, res);
							return ;
						});
					});
				});
			});
		});	

	});

}